package cn.yhr.summerboot.context;

import cn.yhr.summerboot.context.annon.SummerBoot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;

/**
 * @Tittle SummerApplication
 * @Description
 * @Author yhr
 * @Date 2018/11/26 10:05
 * @Version 1.0
 */
public class SummerApplication {

    private Logger logger = LoggerFactory.getLogger(SummerApplication.class);

    private Environment environment;

    public SummerApplication(String[] args) {
        initEnvironment(args);
    }

    private void initEnvironment(String[] args) {
        this.environment = new Environment(args);
    }

    public static void start(Class mainClass, String[] args){
        if(mainClass.getAnnotation(SummerBoot.class) !=null){
            new SummerApplication(args).init(mainClass);
        }
    }

    public void init(Class mainClass){
        long start = System.currentTimeMillis();
        //初始化带注解的bean
        initAnnoClasses(mainClass.getPackage().getName());
        //把@Bean注解的放入Ioc容器
        initIocClassMethodInject();
        //初始化自动注入
        autowiredAttribute();
        //日志
        logInfo(start);

        //判断是否为web环境 启动web

    }

    private void initIocClassMethodInject() {
        try {
            new BeanAnnotationProcessor().findBeanAnnoInClasses();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化包路径所在类
     */
//    private void scanningTotalClasses(String packages) {
//        PackageScanner.setPackages(packages);
//    }

    /**
     * 初始化auto注解属性
     */
    private void autowiredAttribute(){
        new AutowiredAnnotationProcessor().findAutoAnnoInClasses();
    }

    /**
     * 初始化包路径所在注解类
     */
    private void initAnnoClasses(String packages) {
        PackageScanner.init(packages);
    }

    private void logInfo(long start) {
        long time=System.currentTimeMillis()-start;
        logger.info(logger.getName()+"Starting beans init in {} ms！",time);
    }

}
